<?php

namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Coreorder;
use app\common\model\UserGroup;
use app\common\model\voucher\Goods;
use app\common\model\voucher\Order;

/**
 * 充值
 */
class Voucher extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['list'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // protected $auth = ['test3'];

    /**
     * 列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':'0','msg':'返回成功'})
     */
    public function list()
    {


        $res = Goods::with(['group'])->order('money asc')->select();
        $this->success('', $res);
    }


    /**
     * 下单
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=false, sample="", description="ID")
     * @ApiParams (name="money", type="integer", required=false, sample="", description="金额")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function addorder()
    {
        $user = $this->auth->getUser();
        $rej = $this->validate(
            $this->request->post(),
            [
                'id' => 'gt:0',
                'money' => 'gt:0',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $order_no = Coreorder::getorderno();
        if ($this->request->post('id')) {
            $res = Goods::get($this->request->post('id'));
            if (!$res) {
                $this->error('未找到该数据');
            }
            $group = UserGroup::get($res->group_id);
            $order = Order::create([
                'user_id' => $user->id,
                'order_no' => $order_no,
                'money' => $res->money,
                // 'send_money' => $res->send_money,
                'group_id' => $res->group_id,
                'discount' => isset($group->discount) ? $group->discount : 0,
            ]);
        } elseif ($this->request->post('money')) {
            $order = Order::create([
                'user_id' => $user->id,
                'order_no' => $order_no,
                'money' => abs($this->request->post('money')),
            ]);
        } else {
            $this->responseMsg(1005, [], '参数不足');
        }

        $core = Coreorder::create([
            'module_mark' => 'recharge',
            'fee' => $order['money'],
            'order_id' => $order->id,
            'order_no' => $order_no,
            'user_id' => $user->id,
        ]);

        $this->responseMsg(0, ['core_id' => $core->id]);
    }
}
